import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('./views/home.vue'),
      redirect: '/login',
      children: [
        {
          path: '/homePage',
          component: () => import('./components/homePage.vue'),
        },
        {
          path: '/payCenter',
          component: () => import('./views/payCenter.vue'),
        },
        {
          path: '/clean',
          component: () => import('./views/clean.vue'),
        },
        {
          path: '/fixCenter',
          component: () => import('./views/fixCenter.vue'),
        },
        {
          path: '/orderTemplate',
          component: () => import('./components/orderTemplate.vue'),
        },
        {
          path: '/messageCenter',
          component: () => import('./views/messageCenter.vue'),
        },
        {
          path: '/news',
          component: () => import('./views/news.vue'),
        },
        {
          path: '/newsDetails',
          component: () => import('./components/newsDetails.vue'),
        },
        {
          path: '/orderList',
          component: () => import('./views/orderList.vue'),
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('./views/login.vue'),
    }
  ],
})
// 路由守卫
router.beforeEach((to, from, next) => {
  // 用户访问登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage中获取到保存的token
  const tokenStr = window.localStorage.getItem('userInfo')
  // 没有token，强制跳转到登录页面
  if (!tokenStr) {
    return next('/login')
  }
  // 如果有token 就跳转到下一个页面
  next()
})

export default router
